package com.miui.theme.custom.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.miui.theme.custom.data.ConfigDataStore
import com.miui.theme.custom.utils.MySQLHelper
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

// --- LoginViewModel ---
enum class LoginState { Idle, Loading, Success, Error }

class LoginViewModel(private val configDataStore: ConfigDataStore) : ViewModel() {
    private val _loginState = MutableStateFlow(LoginState.Idle)
    val loginState = _loginState.asStateFlow()

    val configFlow = configDataStore.config

    fun connect() {
        viewModelScope.launch {
            _loginState.value = LoginState.Loading
            val config = configDataStore.config.first()
            if (config == null) {
                _loginState.value = LoginState.Error
                return@launch
            }

            val helper = MySQLHelper(config)
            val result = helper.connect()

            if (result.isSuccess) {
                _loginState.value = LoginState.Success
            } else {
                _loginState.value = LoginState.Error
            }
        }
    }
}